﻿#include "prj_manager_table_widget.h"
#include "ui_prj_manager_table_widget.h"
#include "prj_manager_edit_dialog.h"
#include "table_row_operator_widget.h"
#include <QDateTime>
#include <QUuid>
#include <QMessageBox>
#include "easylogging++.h"
#include "project_info_table.h"

PrjManagerTableWidget::PrjManagerTableWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PrjManagerTableWidget),
    m_sqlOperator(new SqliteManager)
{
    ui->setupUi(this);
    initUi();
    initEvents();
    initPrjData();
}

PrjManagerTableWidget::~PrjManagerTableWidget()
{
    delete ui;
}

void PrjManagerTableWidget::onNewPrjBtnClicked()
{
    PrjManagerEditDialog dialog;
    dialog.setWindowTitle(QStringLiteral("新建项目"));
    int ret = dialog.exec();
    LOG(DEBUG) << "prj manager edit dialog ret: " << ret;
    if (ret)
    {
        QString uuid = QUuid::createUuid().toString(QUuid::WithoutBraces);
        QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss zzz");

        ret = insertNewPrj(uuid, dialog.getPrjName(), dialog.getPrjDescription(), currentTime);
        if (!ret)
        {
            LOG(ERROR) << "insert new prj failed, error info!";
            return ;
        }

        insertRow(uuid, dialog.getPrjName(), dialog.getPrjDescription(), currentTime, currentTime);
    }
}

void PrjManagerTableWidget::onEditPrj(PrjTableData *data, int row)
{
    Q_UNUSED(data)
    PrjManagerEditDialog dialog;
    dialog.setWindowTitle(QStringLiteral("编辑项目"));
    dialog.setPrjName(ui->prjTableWidget->item(row, 0)->text());
    dialog.setPrjDescription(ui->prjTableWidget->item(row, 1)->text());
    int ret = dialog.exec();
    LOG(DEBUG) << "prj manager edit dialog ret: " << ret;
    if (ret)
    {
        QString uuid = ui->prjTableWidget->item(row, 0)->data(Qt::UserRole).toString();
        ProjectInfoTable pit;
        pit.updateProjectBaseInfo(uuid, dialog.getPrjName(), dialog.getPrjDescription());
        ui->prjTableWidget->item(row, 0)->setText(dialog.getPrjName());
        ui->prjTableWidget->item(row, 1)->setText(dialog.getPrjDescription());
    }
}

void PrjManagerTableWidget::onDeletePrj(PrjTableData *data, int row)
{
    QMessageBox msg;
    msg.setText(QStringLiteral("确定删除项目吗？"));
    msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    int msgRet = msg.exec();
    if (QMessageBox::Cancel == msgRet)
    {
        return ;
    }

    QHash<QString, QVariant> whereConditions;
    whereConditions["uuid"] = data->uuid;
    bool ret = m_sqlOperator->deleteData(PRJ_INFO_TABLE_NAME, whereConditions);
    if (!ret)
    {
        LOG(ERROR) << "delete prj data failed, error info: " << m_sqlOperator->lastError().toStdString();
        return ;
    }

    ui->prjTableWidget->removeRow(row);
}

void PrjManagerTableWidget::initUi()
{
    ui->prjTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->prjTableWidget->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
    ui->prjTableWidget->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
    ui->prjTableWidget->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);

    ui->prjTableWidget->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    ui->prjTableWidget->horizontalHeader()->hideSection(1);
    setAttribute(Qt::WA_StyledBackground);
}

void PrjManagerTableWidget::initEvents()
{
    connect(ui->newPrjBtn, &QPushButton::clicked, this, &PrjManagerTableWidget::onNewPrjBtnClicked);
    connect(ui->prjTableWidget, &QTableWidget::cellDoubleClicked, this, [=](int row, int column){
        Q_UNUSED(column)
        QWidget* widget = ui->prjTableWidget->cellWidget(row, 4);
        TableRowOperatorWidget *operatorWidget = qobject_cast<TableRowOperatorWidget*>(widget);
        PrjTableData* data = operatorWidget->tableData();
        emit(prjDoubleClicked(ui->prjTableWidget->item(row, 0)->text(), data->uuid));
    });
    connect(ui->searchBtn, &QPushButton::clicked, this, [=]() {
        QString text = ui->searchLineEdit->text();
        if (text.isEmpty()) {
            initPrjData();
        }
        else {
            loadPrjDataOnPrjNameContainsText(text);
        }
    });
}

void PrjManagerTableWidget::clearPrjDataTable()
{
    for (int row = ui->prjTableWidget->rowCount(); row >= 0; row--)
    {
        ui->prjTableWidget->removeRow(row);
    }
}

void PrjManagerTableWidget::initPrjData()
{
    clearPrjDataTable();
    QList<QVariantList> data;
    ProjectInfoTable pit;
    pit.getAllProjectInfo(data);

    for (int i = 0; i < data.size(); i++)
    {
        insertRow(data[i][0].toString(),
                  data[i][1].toString(),
                  data[i][2].toString(),
                  data[i][3].toString(),
                  data[i][4].toString());
    }
}

void PrjManagerTableWidget::loadPrjDataOnPrjNameContainsText(QString text)
{
    clearPrjDataTable();
    QList<QVariantList> data;
    ProjectInfoTable pit;
    pit.getProjectInfoOnProjectNameContainsText(text, data);

    for (int i = 0; i < data.size(); i++)
    {
        insertRow(data[i][0].toString(),
                  data[i][1].toString(),
                  data[i][2].toString(),
                  data[i][3].toString(),
                  data[i][4].toString());
    }
}

void PrjManagerTableWidget::insertRow(QString uuid, QString prjName, QString prjDesc, QString createTime, QString lastModifyTime)
{
    ui->prjTableWidget->insertRow(0);
    ui->prjTableWidget->setItem(0, 0, new QTableWidgetItem(prjName));
    ui->prjTableWidget->setItem(0, 1, new QTableWidgetItem(prjDesc));
    ui->prjTableWidget->item(0, 0)->setData(Qt::UserRole, uuid);
    QDateTime createDateTime = QDateTime::fromString(createTime, "yyyy-MM-dd hh:mm:ss zzz");
    QString createDays = QString::number(createDateTime.daysTo(QDateTime::currentDateTime()));
    createDays += QStringLiteral("天前");
    ui->prjTableWidget->setItem(0, 2, new QTableWidgetItem(createDays));
    QDateTime modifyDateTime = QDateTime::fromString(lastModifyTime, "yyyy-MM-dd hh:mm:ss zzz");
    QString modifyDays = QString::number(modifyDateTime.daysTo(QDateTime::currentDateTime()));
    modifyDays += QStringLiteral("天前");
    ui->prjTableWidget->setItem(0, 3, new QTableWidgetItem(modifyDays));

    PrjTableData *tableData = new PrjTableData;
    tableData->uuid = uuid;
    TableRowOperatorWidget *operatorWidget = new TableRowOperatorWidget(this);
    operatorWidget->setTableData(tableData);
    ui->prjTableWidget->setCellWidget(0, 4, operatorWidget);

    connect(operatorWidget, &TableRowOperatorWidget::editData, this, [=]() {
        PrjTableData *prjData = (PrjTableData*)operatorWidget->tableData();
        int x = operatorWidget->frameGeometry().x();
        int y = operatorWidget->frameGeometry().y();
        // 根据按钮的x和y坐标来定位对应的单元格
        QModelIndex index = ui->prjTableWidget->indexAt(QPoint(x, y));
        onEditPrj(prjData, index.row());
    });
    connect(operatorWidget, &TableRowOperatorWidget::deleteData, this, [=]() {
        PrjTableData *prjData = (PrjTableData*)operatorWidget->tableData();
        int x = operatorWidget->frameGeometry().x();
        int y = operatorWidget->frameGeometry().y();
        // 根据按钮的x和y坐标来定位对应的单元格
        QModelIndex index = ui->prjTableWidget->indexAt(QPoint(x, y));
        onDeletePrj(prjData, index.row());
    });
}

bool PrjManagerTableWidget::insertNewPrj(QString uuid, QString prjName, QString prjDesc, QString createTime)
{
    QList<QString> fields;
    fields << "uuid" << "prj_name" << "prj_description" << "create_time" << "last_modify_time";

    QVariantList data;
    data << uuid << prjName << prjDesc << createTime << createTime;
    int ret = m_sqlOperator->insertRowData(PRJ_INFO_TABLE_NAME, fields, data);
    if (!ret)
    {
        LOG(ERROR) << "insert new prj failed, error info: " << m_sqlOperator->lastError().toStdString();
    }

    return ret;
}

